<template>
  <view>
    <uni-search-bar @confirm="search" @input="input" :radius="100" cancelButton="none"></uni-search-bar>
    <uni-list v-if="searchResults.length>0">
      <uni-list-item
        showArrow
        :ellipsis="1"
        :title="item.goods_name"
        v-for="(item, index) in searchResults"
        :key="index"
        :to="`/subpkg/goods_detail/goods_detail?goods_id=${item.goods_id}`"
      />
    </uni-list>  
    <view class="history-box" v-else>
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" @click="clearSearchHistory"></uni-icons>
      </view>
      <view class="history-list"><uni-tag v-for="(item, index) in historys" :key="index" :text="item" @click="gotoGoodsList(item)"></uni-tag></view>
    </view>
  </view>
</template>

<script>
import uniSearchBar from '../../uni_modules/uni-search-bar/components/uni-search-bar/uni-search-bar.vue';
import { debounce } from 'lodash';
export default {
  components: { uniSearchBar },
  data() {
    return {
      timer: null,
      searchResults: [], //搜索结果
      historyList: uni.getStorageSync('kw')?JSON.parse(uni.getStorageSync('kw')): [] //搜索历史
    };
  },
  methods: {
    clearSearchHistory(){
      this.historyList = []
       uni.setStorageSync('kw', '[]')
    },
    gotoGoodsList(query){
      uni.navigateTo({
        url: "/subpkg/goods_list/goods_list?query="+query
      })
    },
    input: debounce(function(e) {
      this.getSearchList(e);
      this.saveSearchHistory(e)
    }, 500),
    async getSearchList(query) {
      if (!query) return (this.searchResults = []);
      let { data: res } = await uni.$http.get('/goods/qsearch', { query });
      if (res.meta.status !== 200) return uni.$showMsg();
      this.searchResults = res.message;
    },
    saveSearchHistory(query){
      //方式1.通过判断,来保证去重
      // if(this.historyList.find(t=>t === query)) return
      //方式2.通过set数据类型
      //set里面存储数据自动去重
      let set = new Set(this.historyList)
      set.add(query)
      this.historyList = [...set]
      //持久化数据
      uni.setStorageSync('kw', JSON.stringify(this.historyList))
    }
  },
  computed: {
    //方式2,数组的翻转
    historys(){
      return this.historyList.reverse()
    }
  }
};
</script>

<style lang="scss">
.history-box {
  padding: 0 5px;
}
.history-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
  font-size: 13px;
  border-bottom: 1px solid #efefef;
}
.uni-tag {
  margin-top: 5px;
  margin-right: 5px;
}
</style>
